 <!--
* description: 保养项目
* author: wangjuan
* createdDate: 2020-11-17
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-api-config="apiConfig"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import api from "@/api/subsidyManage";
import { vehiclePdiPriceInquirys } from "@/api/se/vehiclePdiPriceInquiry";
import Vue from "vue";
import request from '@/utils/request';

export default {
  name: "MaintenanceProgram",

  components: {
    OneTableTemplate,
    Edit: () => import("./edit"),
  },

  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ""], function () {
      next();
    });
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);

    return {
      // 网格查询API配置对象
      apiConfig: vehiclePdiPriceInquirys.queryMaintenanceItem,
      editRowData: {},
      selectData: {},
      editPopupsVisible: false,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          name: "search",
          clickEvent: () => this.queryTable(1),
          text: this.$t("sys.button.query"), // 查询
          position: "right",
          fuzzySearch: true,
        },
        {
          compKey: "btnKey2",
          size: "small",
          name: "reset",
          clickEvent: () => this.reset(),
          text: this.$t("sys.button.reset"),
          position: "right", // 重置
        },
        {
          compKey: "btnKey3",
          size: "small",
          name: "add",
          clickEvent: () => this.add(),
          text: this.$t("sys.button.add"),
          position: "left", // 新增
        },
        {
          compKey: "btnKey4",
          size: "small",
          name: "importTemplate",
          position: "upload",
          clickEvent: () => this.handFileListChange(),
          text: "导入",
        },
        {
          compKey: "btnKey5",
          type: "text",
          size: "small",
          position: "upload",
          click: (event) => {
            this.templateDownload();
          },
        },
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
              .tableComponents
          : [
              // {
              //   compKey: "compKey1",
              //   labelName: "车系：",
              //   codeField: "colNtatusName",
              //   lookuptype: "VE1086",
              //   component: () => import("@/components/org/LookupValue"),
              //   type: "dropdownList",
              //   isMul: false,
              //   isMust: false,
              // },
              // {
              //   compKey: "compKey2",
              //   labelName: "车型：",
              //   codeField: "carTypeCode",
              //   oFields: "carTypeCode,carTypeCn",
              //   component: () => import("@/components/org/commonSelect"),
              //   customObj: {
              //     api: {
              //       APIUrl:
              //         "/mp/e3sh/aftersale/maintenanceItemService/workRelaCarType.do",
              //     },
              //     selectType: "1",
              //   },
              //   type: "dropdownList",
              //   isMul: false,
              //   isMust: true,
              // },
              {
                compKey: 'compKey1',
                labelName: '车系：',
                codeField: 'carSeriesCode',
                component: () => import('@/components/org/commonSelect'),
                oFields: 'carSeriesCode,carSeriesCn',
                customObj: {
                  api: vehiclePdiPriceInquirys.queryCarSeries,
                  selectType: '1'
                },
                isMul: false,
                isMust: true
              },
              {
                compKey: 'compKey2',
                labelName: '车型：',
                codeField: 'carConfigCode',
                textField: 'carConfigCn',
                component: () => import('@/components/org/commonSelect'),
                oFields: 'carConfigCode,carConfigCn',
                parentFileds: 'value:carSeriesCode-carSeriesCode,disabled:carSeriesCode-carConfigCode--false',
                customObj: {
                  api: vehiclePdiPriceInquirys.queryCarType,
                  listQuery: {
                    carSeriesCode: ''
                  },
                  selectType: '1'
                },
                disabled: true,
                isMul: false,
                isMust: true
              },
              {
                compKey: "compKey3",
                labelName: "保养项目编码：",
                codeField: "repairModeCode",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey4",
                labelName: "保养项目名称：",
                codeField: "repairModeName",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey5",
                labelName: "状态：",
                codeField: "isEnable",
                component: () => import("@/components/org/LookupValue"),
                oFields: "statusId,statusText",
                type: "dropdownList",
                options: [
                  { statusId: "1", statusText: "启用" },
                  { statusId: "0", statusText: "停用" },
                ],
                isMul: false,
                isMust: true,
              },
            ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "subsidyId",
                label: "主键ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "updateControlId",
                label: "并发控制ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "controlBtn",
                label: "操作",
                width: 100,
                fixed: true,
                isComponent: true,
                comps: [
                  {
                    compKey: "propKey1",
                    labelName: "修改",
                    component: () => import("@/components/org/linkButton"),
                    clickEvent: (index) => this.edit(index),
                  },
                ],
              },
              {
                prop: "repairModeCode",
                label: "保养项目编码",
              },
              {
                prop: "repairModeName",
                label: "保养项目名称",
              },
              {
                prop: "repairModeContent",
                label: "保养项目描述",
              },
              // {
              //   prop: "orgTypeName",
              //   label: "车系",
              // },
              {
                prop: "carTypeCn",
                label: "车型",
              },
              {
                prop: "isEnableCn",
                label: "状态",
              },
            ],

      // 表单数据
      formField: this.$utils.getFormField(
        this,
        {
          repairModeCode: "", //保养项目编码
          repairModeName: "", //保养项目名称
          repairModeContent: "", //保养项目描述
          isEnable: "", //状态
          //carTypeCode: "", //车型
          carSeriesCode: "",//车系
          carConfigCode: "",//车型
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
    };
  },

  mounted() {
    // 列表查询
    this.queryTable(1);
  },

  methods: {
    edit(index) {
      this.editPopupsState = "edit";
      this.editPopupsVisible = true;
      this.editRowData = this.$utils.deepCopy(
        this.$refs["multipleTable"].list[index]
      );
    },
    close() {
      this.editPopupsVisible = false;
      this.queryTable(1);
    },

    templateDownload() {
      const fileName = this.$utils.fileNameWithTime("保养项目.xlsx");
      this.$requestAPI({
        apiUrl: "/mp/e3sh/aftersale/maintenanceItemService/downloadTemplate.do",
        variables: { dataType: "excel" },
      })
        .then((res) => {
          this.$utils.downloadFile(res, fileName);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file);
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: "文件大小不能超过50M",
          type: "warning",
        });
        return false;
      }
      let fileType = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (fileType != "xls" && fileType != "xlsx") {
        this.$message({
          message: "只能导入后缀为xls,xlsx的文件！",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: "导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const that = this;
      const url =
        "/mp/e3sh/aftersale/maintenanceItemService/importMaintenanceItem.do";
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close();
          if (response.result === "1") {
            this.$message({
              message: "导入成功",
              type: "success",
            });
            that.queryTable();
          } else {
            this.$message({
              message: response.msg,
              type: "warning",
            });
          }
        })
        .catch((err) => {});
    },
    // 查询车型
    queryCar() {
      request({
        url: vehiclePdiPriceInquirys.queryCarType.APIUrl,
        method: 'post',
        data: {
          CAR_SERIES_CODE: this.formField.CAR_SERIES_CODE
        }
      }).then(res => {
        res.rows.map(item => {
          this.tableComponents[1].options.push({
            label: item.carConfigCn,
            value: item.carConfigCode
          })
        })
      })
    }
  },
  watch: {
    'formField.CAR_SERIES_CODE': {
      handler: function(Val) {
        if (Val) {
          this.queryCar()
        } 
      }
    },
    'formField.carSeriesCode': {
      handler(newval,oldval){
        if (!newval) {
          this.formField.carConfigCode=""
        }
      }
    }
  },
};
</script>
